"""
【记录状态可回滚】
备忘录模式(Memento Pattern)
允许在不破坏封装性的前提下，捕获并保存一个对象的内部状态，以便可以将该对象恢复到原先保存的状态。这个模式通常用于需要撤销操作的场景。
"""


class Memento:  # 一个类记录状态返回状态
    def __init__(self, state):
        self.state = state

    def get_state(self):
        return self.state


class Originator:
    def __init__(self, state):
        self.state = state

    def create_memento(self):
        return Memento(self.state)

    def restore_memento(self, memento):
        self.state = memento.get_state()

    def set_state(self, state):
        self.state = state

    def get_state(self):
        return self.state


class Caretaker:
    def __init__(self, originator):
        self.mementos = []
        self.originator = originator

    def save_state(self):
        memento = self.originator.create_memento()
        self.mementos.append(memento)

    def restore_last_state(self):
        if len(self.mementos) > 0:
            memento = self.mementos.pop()
            self.originator.restore_memento(memento)


originator = Originator("State A")
caretaker = Caretaker(originator)

print(originator.get_state())
caretaker.save_state()

originator.set_state("State B")
print(originator.get_state())

caretaker.save_state()
originator.set_state("State C")
print(originator.get_state())

caretaker.restore_last_state()
print(originator.get_state())

caretaker.restore_last_state()
print(originator.get_state())
"""
State A
State B
State C
State B
State A
"""
